import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { sessionStorage } from '@/utils/storage';
import { ElLoading, ElMessage } from 'element-plus';
import router from '@/router';
import type { LoadingInstance } from 'element-plus/es/components/loading/src/loading';

let downloadLoadingInstance: LoadingInstance;

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  withCredentials: false
});

service.interceptors.request.use(
  function (config) {
    config.headers.token = sessionStorage.get('token');
    if (config.headers['X-Show-Loading'] !== 'false') {
      downloadLoadingInstance = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  function (resp: AxiosResponse) {
    // 响应之后就关闭弹窗
    if (downloadLoadingInstance) {
      downloadLoadingInstance.close();
    }
    // 二进制数据则直接返回
    if (resp.request.responseType === 'blob' || resp.request.responseType === 'arraybuffer') {
      return resp.data;
    }
    // 如果响应数据有code、msg就提示。
    if (resp.data.code && resp.data.code === 200 && resp.data.msg) {
      // 如果msg前四位是http就不弹框了
      if (resp.data.msg.substring(0, 4) !== 'http') {
        ElMessage.success(resp.data.msg);
      }
      return resp.data;
    }
    // 未设置状态码则默认成功状态
    const code = resp.data.code || 200;
    // 获取错误信息
    const msg = resp.data.msg || '系统未知错误';

    if (code === 401) {
      ElMessage.error(msg);
      sessionStorage.remove('token');
      router.push({
        path: '/login',
        query: { redirect: router.currentRoute.value.fullPath }
      });
      return Promise.reject(resp);
    } else if (code === 501 || code === 412) {
      // 501非空拦截  412逻辑拦截
      ElMessage.warning(msg);
      return Promise.reject(resp);
    } else if (code === 500) {
      ElMessage.error(msg);
      return Promise.reject(new Error(msg));
    } else if (code !== 200) {
      ElMessage.error(msg);
      return Promise.reject(resp);
    } else {
      return resp.data;
    }
  },
  function (error) {
    if (downloadLoadingInstance) {
      downloadLoadingInstance.close();
    }
    if (error.response && error.response.status && error.response.status === 401) {
      ElMessage.error('登录过期，请重新登录');
      sessionStorage.remove('token');
      router.push({
        path: '/login',
        query: { redirect: router.currentRoute.value.fullPath }
      });
      return;
    }
    let message = '请求失败';
    if (error.message === 'Network Error') {
      message = '网络错误，请检查您的网络连接';
    } else if (error.message.includes('timeout')) {
      message = '请求超时，请稍后重试';
    } else if (error.message.includes('Request failed with status code')) {
      message = '请求失败，请检查您的网络连接或稍后重试';
    }
    ElMessage.error(message);
    return Promise.reject(error);
  }
);

// 封装 GET 请求
export function apiGet(url: string, params?: any, config?: AxiosRequestConfig): Promise<any> {
  return service.get(url, { params, ...config });
}

// 封装 POST 请求
export function apiPost(url: string, data?: any, config?: AxiosRequestConfig): Promise<any> {
  return service.post(url, data, config);
}

export default service;